#include <bits/stdc++.h>

using namespace std;

class Solution
{
public:
    int countPaths(vector<vector<int>> &grid)
    {
        int n = grid.size(), m = grid[0].size();
        vector<vector<int>> intG(n, vector<int>(m));
        vector<vector<int>> methods(n, vector<int>(m, 1));
        int dr[4][2] = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
        int MOD = 1'000'000'007;
        int ans = 0;
        typedef pair<int, int> pii;
        queue<pii> q;
        for (int i = 0; i < n; ++i)
        {
            for (int j = 0; j < m; ++j)
            {
                for (int k = 0; k < 4; ++k)
                {
                    int ni = i + dr[k][0], nj = j + dr[k][1];
                    if (ni >= 0 && ni < n && nj >= 0 && nj < m && grid[i][j] > grid[ni][nj])
                    {
                        ++intG[i][j];
                    }
                }
                if (intG[i][j] == 0)
                {
                    q.push({i, j});
                    ans = (ans + methods[i][j]) % MOD;
                }
            }
        }
        while (!q.empty())
        {
            int qsize = q.size();
            while (qsize--)
            {
                auto node = q.front();
                q.pop();
                auto [i, j] = node;
                for (int k = 0; k < 4; ++k)
                {
                    int ni = i + dr[k][0], nj = j + dr[k][1];
                    if (ni >= 0 && ni < n && nj >= 0 && nj < m && grid[ni][nj] > grid[i][j])
                    {
                        methods[ni][nj] = (methods[ni][nj]+methods[i][j]) % MOD;
                        if (--intG[ni][nj] == 0)
                        {
                            q.push({ni, nj});
                            ans = (ans + methods[ni][nj]) % MOD;
                        }
                    }
                }
            }
        }
        return ans;
    }
};

int main()
{

    // system("pause");
    return 0;
}
